package com.husd.framework.zookeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.CreateBuilder;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 这里是这个类的功能描述
 *
 * @author hushengdong
 * @date 2021/5/12
 */
public class CuratorFrameworkTest {

    private static String serverList = "127.0.0.1:2181";

    public static void main(String[] args) throws Exception {

        CuratorFramework curatorFramework = getZkClient();

        //创建节点
        String path = "/test";
        Stat stat  = curatorFramework.checkExists().forPath(path);
        if(stat != null) {
            //删除节点
            curatorFramework.delete().forPath(path);
        }

        String content = "this contents 12345";
        //创建节点 并且 设置数据
        curatorFramework.create()
                .withMode(CreateMode.PERSISTENT)
                .forPath(path,content.getBytes());

        //查询节点
        byte [] bytes = curatorFramework.getData().forPath(path);
        System.out.println("结果:" + new String(bytes));

        curatorFramework.close();
    }

    private static CuratorFramework getZkClient() {
        ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 3, 5000);
        CuratorFramework zkClient = CuratorFrameworkFactory.builder()
                .namespace("curator")
                .connectString(serverList)
                .sessionTimeoutMs(5000)
                .connectionTimeoutMs(5000)
                .retryPolicy(retryPolicy)
                .build();
        zkClient.start();
        return zkClient;
    }
}
